package org.ruoyi.interview.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.ruoyi.interview.config.XunfeiSparkConfig;
import org.ruoyi.interview.service.IInterviewAIService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonElement;
import com.google.gson.JsonArray;

/**
 * 面试AI服务实现类
 *
 * @author ruoyi
 */
@Slf4j
@Service
public class InterviewAIServiceImpl implements IInterviewAIService {

    @Autowired
    private XunfeiSparkConfig xunfeiSparkConfig;

    /**
     * 调用讯飞星火大模型API回答问题
     *
     * @param question 用户问题
     * @return 模型回答
     * @throws Exception 调用异常
     */
    @Override
    public String askModel(String question) throws Exception {
        try {
            RestTemplate restTemplate = createRestTemplate();

            // 构造请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            // 构造请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("header", Map.of("app_id", xunfeiSparkConfig.getAppId()));
            requestBody.put("parameter", Map.of("chat", Map.of("domain", "general", "temperature", 0.5, "max_tokens", 2048)));
            
            Map<String, Object> payload = new HashMap<>();
            Map<String, Object> message = new HashMap<>();
            List<Map<String, String>> text = new ArrayList<>();
            text.add(Map.of("role", "user", "content", question));
            message.put("text", text);
            payload.put("message", message);
            requestBody.put("payload", payload);

            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

            // 获取API URL
            String apiUrl = "https://spark-api-open.xf-yun.com/v1/chat/completions";
            
            // 如果DNS解析失败，尝试使用备用IP地址
            String finalUrl = resolveUrlWithFallback(apiUrl);

            // 发送POST请求
            ResponseEntity<String> response = restTemplate.postForEntity(
                    finalUrl, requestEntity, String.class);
            
            // 解析响应结果
            return parseXunfeiResponse(response.getBody());
        } catch (ResourceAccessException e) {
            log.error("调用讯飞星火API网络连接失败", e);
            throw new Exception("调用AI服务失败: 网络连接异常，请检查网络设置或API地址配置", e);
        } catch (RestClientException e) {
            log.error("调用讯飞星火API失败", e);
            throw new Exception("调用AI服务失败: 网络请求异常", e);
        } catch (Exception e) {
            log.error("处理AI服务响应时发生错误", e);
            throw new Exception("处理AI服务响应失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 解析讯飞星火API的响应
     * 
     * @param responseBody 响应体
     * @return AI回答内容
     */
    private String parseXunfeiResponse(String responseBody) throws Exception {
        try {
            JsonObject responseJson = JsonParser.parseString(responseBody).getAsJsonObject();
            
            // 检查是否有错误
            if (responseJson.has("error")) {
                JsonObject error = responseJson.getAsJsonObject("error");
                String errorMessage = error.has("message") ? error.get("message").getAsString() : "未知错误";
                throw new Exception("讯飞星火API返回错误: " + errorMessage);
            }
            
            // 解析正常响应
            if (responseJson.has("choices")) {
                JsonArray choices = responseJson.getAsJsonArray("choices");
                if (choices.size() > 0) {
                    JsonObject choice = choices.get(0).getAsJsonObject();
                    if (choice.has("message")) {
                        JsonObject message = choice.getAsJsonObject("message");
                        if (message.has("content")) {
                            return message.get("content").getAsString();
                        }
                    }
                }
            }
            
            throw new Exception("无法从响应中提取AI回答内容: " + responseBody);
        } catch (Exception e) {
            log.error("解析讯飞星火API响应失败，响应内容: {}", responseBody, e);
            throw new Exception("解析AI服务响应失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 解析URL，如果DNS解析失败则使用备用IP地址
     * 
     * @param originalUrl 原始URL
     * @return 解析后的URL
     */
    private String resolveUrlWithFallback(String originalUrl) {
        try {
            // 尝试解析域名
            String host = "spark-api-open.xf-yun.com";
            InetAddress address = InetAddress.getByName(host);
            log.info("域名解析成功: {} -> {}", host, address.getHostAddress());
            return originalUrl;
        } catch (UnknownHostException e) {
            log.warn("域名解析失败: {}, 尝试使用备用API地址", e.getMessage());
            // 使用备用API地址
            String fallbackUrl = originalUrl.replace("spark-api-open.xf-yun.com", "47.110.138.66");
            log.info("使用备用API地址: {}", fallbackUrl);
            return fallbackUrl;
        }
    }
    
    /**
     * 创建配置了超时和代理的RestTemplate实例
     * 
     * @return RestTemplate实例
     */
    private RestTemplate createRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        // 连接超时时间(毫秒)
        requestFactory.setConnectTimeout(10000);
        // 读取超时时间(毫秒)
        requestFactory.setReadTimeout(30000);
        
        restTemplate.setRequestFactory(requestFactory);
        return restTemplate;
    }
}